<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    //用户添加
    public function getAdd()
    {
    	// 解析模板 
    	return view('Admin.user.add');
    }

    // 添加用户
    public function postInsert(Request $request)
    {
        $this->validate($request, [
        'name' => 'required|max:15',
        'password' => 'required',
        'repassword' => 'required|same:password',
        'email' => 'required|email',
        'phone' => 'required|regex:[1\d{10}]',

    ],[
    	'name.required' => '用户名不能为空',
    	'name.max' => '请输入6-15位用户名',
    	'password.required' => '密码不能为空',
    	'repassword.required' => '密码不能为空',
    	'repassword.same' => '两次密码不一致',
    	'email.required' => '邮箱不能为空',
    	'email.email' => '邮箱格式不正确',
    	'phone.required' => '手机号不能为空',
    	'phone.regex' => '手机号格式不正确',
    ]);	
        $data = $request -> only(['name','password','email','phone']);
        $data['token'] = str_random(50);

        // 执行插入
        $res = DB::table('user') -> insert($data);

        if($res){
        	return redirect('/admin/user/index') -> with('success','用户添加成功');
        }else{
        	return back() -> with('error','用户添加失败');
        }
    }

    public function getIndex(Request $request)
    {	
    	// 查询用户数据
    	if($request -> input('word')){
    		$user = DB::table('user') -> where('name','like','%'.$request->input('word').'%')->paginate(2);
    	}else{
    		$user = DB::table('user')->paginate(2);
    	}
    	$data = $request -> all();
    	return view('admin.user.index',['user' => $user,'request'=>$data]);
    }

    // 用户修改查询
    public function getEdit($id)
    {
    	$user = DB::table('user') -> where('id',$id) -> first();
    	// dd($user);
    	// 解析模板
    	return view('admin.user.edit',['user' => $user]);
    }

    // 修改数据
    public function postUpdate(Request $request)
    {	
    	// 获取id
    	$id = $request -> only(['id']);
    	//详细信息
    	$data = $request -> only(['name','email','phone']);

    	$res = DB::table('user') -> where('id',$id) -> update($data);
        if($res){
        	return redirect('/admin/user/index') -> with('success','用户修改成功');
        }else{
        	return back() -> with('error','用户修改失败');
        }
    }

    public function postDelete(Request $request)
    {
    	// 获取id
    	$id = $request -> input('id');

    	// 执行删除
    	$res = DB::table('user') -> where('id',$id) -> delete();
    	if($res){
    		echo 1;
    	}else{
    		echo 0;
    	}
    }
}
